"""
游戏页面处理器

专门处理游戏页面的识别和操作
"""

import asyncio
import sys
from typing import Dict, Any, Optional, List
from playwright.async_api import Page

# 添加项目根目录到路径
sys.path.append('k:/Projects/python/gamer520')

from src.browser.page_handler import BasePageHandler
from src.browser.page_handlers.download_button_recognizer import DownloadButtonRecognizer
from src.utils.logger import get_logger

logger = get_logger(__name__)


class GamePageHandler(BasePageHandler):
    """游戏页面处理器类"""
    
    def __init__(self, page: Page):
        super().__init__(page)
        
        # 初始化下载按钮识别器
        self.download_recognizer = DownloadButtonRecognizer(page)
        self.download_button_selectors = [
            # 特定的下载按钮选择器（基于实际页面结构）
            '#cao_widget_pay-4 > div.pay--content > div > a',  # 您提供的具体选择器
            'a.go-down.btn.btn--secondary.btn--block',  # 基于class组合的选择器
            'a.go-down:has-text("立即下载")',  # 结合class和文本的选择器
            'a[class*="go-down"]:has-text("立即下载")',  # 更灵活的class匹配
            
            # 常见的下载按钮选择器
            'button:has-text("立即下载")',
            'a:has-text("立即下载")',
            'button:has-text("下载游戏")',
            'a:has-text("下载游戏")',
            'button:has-text("免费下载")',
            'a:has-text("免费下载")',
            'button:has-text("下载")',
            'a:has-text("下载")',
            
            # 基于图标和文本组合的选择器
            'a:has(.fa-cloud-download):has-text("立即下载")',
            'button:has(.fa-cloud-download):has-text("立即下载")',
            'a:has(i[class*="download"]):has-text("立即下载")',
            'button:has(i[class*="download"]):has-text("立即下载")',
            
            # CSS类名选择器
            '.go-down',  # 新增的特定class
            '.download-btn',
            '.download-button',
            '.btn-download',
            '.game-download',
            '.download-game',
            '.free-download',
            '.btn.btn--secondary.btn--block',  # 基于您提供的样式
            
            # ID选择器
            '#download',
            '#download-btn',
            '#download-button',
            '#game-download',
            
            # 属性选择器
            '[data-action="download"]',
            '[data-type="download"]',
            '[data-id*="download"]',  # 新增data-id属性匹配
            'button[onclick*="download"]',
            'a[href*="download"]',
            'a[target="_blank"]:has-text("立即下载")',  # 基于target属性
            
            # 更通用的选择器
            'button[class*="download"]',
            'a[class*="download"]',
            'button[id*="download"]',
            'a[id*="download"]',
            'a[class*="btn"][class*="secondary"]:has-text("下载")',  # 基于按钮样式
            'a[class*="go-down"]',  # 基于go-down class
        ]
        
        self.play_button_selectors = [
            # 开始游戏按钮
            'button:has-text("开始游戏")',
            'a:has-text("开始游戏")',
            'button:has-text("进入游戏")',
            'a:has-text("进入游戏")',
            'button:has-text("立即游戏")',
            'a:has-text("立即游戏")',
            'button:has-text("开始")',
            'button:has-text("游戏")',
            
            # CSS类名
            '.play-btn',
            '.start-game',
            '.game-start',
            '.btn-play',
            
            # ID选择器
            '#play',
            '#start',
            '#play-button',
            '#start-game'
        ]
    
    async def handle(self) -> Dict[str, Any]:
        """
        处理游戏页面
        
        Returns:
            Dict: 处理结果
        """
        try:
            # 等待页面加载
            await self.wait_for_page_load()
            
            # 首先处理弹窗
            await self.close_all_popups()
            
            # 识别页面类型
            page_type = await self.identify_game_page_type()
            
            # 查找下载按钮
            download_button = await self.find_download_button()
            
            # 查找游戏按钮
            play_button = await self.find_play_button()
            
            # 检查页面状态
            page_status = await self.check_page_status()
            
            result = {
                'page_type': page_type,
                'download_button': download_button,
                'play_button': play_button,
                'page_status': page_status,
                'has_download_button': download_button is not None,
                'has_play_button': play_button is not None,
                'recommended_action': await self.get_recommended_action(download_button, play_button, page_type)
            }
            
            self.logger.info(f"游戏页面处理完成: {page_type}")
            return result
            
        except Exception as e:
            self.logger.error(f"游戏页面处理失败: {str(e)}")
            return {'error': str(e), 'page_type': 'unknown'}
    
    async def identify_game_page_type(self) -> str:
        """
        识别游戏页面类型
        
        Returns:
            str: 页面类型 ('download_page', 'play_page', 'mixed_page', 'unknown')
        """
        try:
            has_download = await self.has_download_elements()
            has_play = await self.has_play_elements()
            
            if has_download and has_play:
                return 'mixed_page'
            elif has_download:
                return 'download_page'
            elif has_play:
                return 'play_page'
            else:
                return 'unknown'
                
        except Exception as e:
            self.logger.error(f"识别页面类型失败: {str(e)}")
            return 'unknown'
    
    async def has_download_elements(self) -> bool:
        """
        检查页面是否有下载相关元素
        
        Returns:
            bool: 是否有下载元素
        """
        try:
            for selector in self.download_button_selectors[:5]:  # 检查前5个最常见的
                element = await self.page.query_selector(selector)
                if element and await element.is_visible():
                    return True
            return False
        except Exception as e:
            self.logger.debug(f"检查下载元素失败: {str(e)}")
            return False
    
    async def has_play_elements(self) -> bool:
        """
        检查页面是否有游戏相关元素
        
        Returns:
            bool: 是否有游戏元素
        """
        try:
            for selector in self.play_button_selectors[:5]:  # 检查前5个最常见的
                element = await self.page.query_selector(selector)
                if element and await element.is_visible():
                    return True
            return False
        except Exception as e:
            self.logger.debug(f"检查游戏元素失败: {str(e)}")
            return False
    
    async def find_download_button(self) -> Optional[Dict[str, Any]]:
        """
        查找下载按钮（使用专门的识别器）
        
        Returns:
            Dict: 下载按钮信息
        """
        try:
            # 使用专门的下载按钮识别器
            return await self.download_recognizer.find_download_button()
            
        except Exception as e:
            self.logger.error(f"查找下载按钮失败: {str(e)}")
            return None
    
    async def find_play_button(self) -> Optional[Dict[str, Any]]:
        """
        查找游戏按钮
        
        Returns:
            Dict: 游戏按钮信息
        """
        try:
            for selector in self.play_button_selectors:
                try:
                    element = await self.page.query_selector(selector)
                    if element and await element.is_visible():
                        is_enabled = await element.is_enabled()
                        if not is_enabled:
                            continue
                        
                        button_info = await self._get_button_info(element, selector, 'play')
                        
                        if await self._validate_play_button(button_info):
                            self.logger.info(f"找到有效游戏按钮: {selector}")
                            return button_info
                            
                except Exception as e:
                    self.logger.debug(f"检查游戏按钮 {selector} 失败: {str(e)}")
            
            return await self._smart_find_play_button()
            
        except Exception as e:
            self.logger.error(f"查找游戏按钮失败: {str(e)}")
            return None
    
    async def _get_button_info(self, element, selector: str, button_type: str) -> Dict[str, Any]:
        """
        获取按钮详细信息
        
        Args:
            element: 按钮元素
            selector: 选择器
            button_type: 按钮类型
            
        Returns:
            Dict: 按钮信息
        """
        try:
            return {
                'element': element,
                'selector': selector,
                'type': button_type,
                'text': await element.text_content(),
                'href': await element.get_attribute('href'),
                'onclick': await element.get_attribute('onclick'),
                'data_action': await element.get_attribute('data-action'),
                'position': await element.bounding_box(),
                'is_enabled': await element.is_enabled(),
                'is_visible': await element.is_visible(),
                'tag_name': await element.evaluate('el => el.tagName.toLowerCase()'),
                'class_name': await element.get_attribute('class'),
                'id': await element.get_attribute('id')
            }
        except Exception as e:
            self.logger.error(f"获取按钮信息失败: {str(e)}")
            return {'element': element, 'selector': selector, 'type': button_type}
    
    async def _validate_download_button(self, button_info: Dict[str, Any]) -> bool:
        """
        验证下载按钮的有效性
        
        Args:
            button_info: 按钮信息
            
        Returns:
            bool: 是否有效
        """
        try:
            # 获取按钮基本信息
            text = button_info.get('text', '').lower().strip()
            class_name = button_info.get('class_name', '').lower()
            href = button_info.get('href')
            onclick = button_info.get('onclick')
            data_action = button_info.get('data_action')
            tag_name = button_info.get('tag_name', '')
            
            # 高优先级验证：特定的按钮样式
            # 1. 检查是否包含"立即下载"文本（最高优先级）
            if '立即下载' in text:
                self.logger.info(f"验证通过：包含'立即下载'文本")
                return True
            
            # 2. 检查是否有go-down class（特定样式）
            if 'go-down' in class_name:
                self.logger.info(f"验证通过：包含'go-down' class")
                return True
            
            # 3. 检查是否有btn--secondary和btn--block class组合
            if 'btn--secondary' in class_name and 'btn--block' in class_name:
                self.logger.info(f"验证通过：包含btn--secondary和btn--block class组合")
                return True
            
            # 4. 检查是否有target="_blank"属性且包含下载相关文本
            if button_info.get('element'):
                try:
                    target = await button_info['element'].get_attribute('target')
                    if target == '_blank' and any(keyword in text for keyword in ['下载', 'download']):
                        self.logger.info(f"验证通过：target='_blank'且包含下载文本")
                        return True
                except:
                    pass
            
            # 5. 检查是否包含FontAwesome下载图标
            if button_info.get('element'):
                try:
                    if await self._has_download_icon(button_info['element']):
                        self.logger.info(f"验证通过：包含下载图标")
                        return True
                except:
                    pass
            
            # 中等优先级验证：通用下载关键词
            download_keywords = ['下载', 'download', '获取', 'get', '安装', 'install']
            if any(keyword in text for keyword in download_keywords):
                # 进一步验证是否有有效的链接或点击事件
                if href and ('download' in href.lower() or 'get' in href.lower() or 'file' in href.lower()):
                    self.logger.info(f"验证通过：包含下载关键词且有有效链接")
                    return True
                
                if onclick and ('download' in onclick.lower() or 'get' in onclick.lower()):
                    self.logger.info(f"验证通过：包含下载关键词且有点击事件")
                    return True
                
                if data_action and ('download' in data_action.lower()):
                    self.logger.info(f"验证通过：包含下载关键词且有data-action")
                    return True
                
                # 如果是按钮标签且有相关类名，也认为有效
                if tag_name == 'button' and any(keyword in class_name for keyword in ['download', 'btn']):
                    self.logger.info(f"验证通过：按钮标签且有相关类名")
                    return True
                
                # 如果是链接标签且有相关类名，也认为有效
                if tag_name == 'a' and any(keyword in class_name for keyword in ['download', 'btn', 'button']):
                    self.logger.info(f"验证通过：链接标签且有相关类名")
                    return True
                
                # 对于包含下载关键词的按钮，给予更宽松的验证
                self.logger.info(f"验证通过：包含下载关键词（宽松验证）")
                return True
            
            # 低优先级验证：基于class名称的验证
            download_class_keywords = ['download', 'btn', 'button', 'go-down']
            if any(keyword in class_name for keyword in download_class_keywords):
                self.logger.info(f"验证通过：包含下载相关class")
                return True
            
            self.logger.debug(f"验证失败：按钮不符合下载按钮特征 - 文本: {text}, class: {class_name}")
            return False
            
        except Exception as e:
            self.logger.debug(f"验证下载按钮失败: {str(e)}")
            return False
    
    async def _validate_play_button(self, button_info: Dict[str, Any]) -> bool:
        """
        验证游戏按钮的有效性
        
        Args:
            button_info: 按钮信息
            
        Returns:
            bool: 是否有效
        """
        try:
            text = button_info.get('text', '').lower()
            if not any(keyword in text for keyword in ['游戏', 'play', '开始', 'start', '进入', 'enter']):
                return False
            
            return True
            
        except Exception as e:
            self.logger.debug(f"验证游戏按钮失败: {str(e)}")
            return False
    
    async def _smart_find_download_button(self) -> Optional[Dict[str, Any]]:
        """
        智能查找下载按钮
        
        Returns:
            Dict: 按钮信息
        """
        try:
            # 查找所有可能的按钮和链接
            all_buttons = await self.page.query_selector_all('button, a, input[type="button"], input[type="submit"]')
            
            for button in all_buttons:
                try:
                    if not await button.is_visible():
                        continue
                    
                    # 获取按钮的文本内容
                    text = await button.text_content()
                    if not text:
                        continue
                    
                    text_lower = text.lower().strip()
                    
                    # 获取按钮的class属性
                    class_attr = await button.get_attribute('class') or ''
                    class_lower = class_attr.lower()
                    
                    # 获取按钮的data-id属性
                    data_id = await button.get_attribute('data-id') or ''
                    
                    # 获取按钮的target属性
                    target = await button.get_attribute('target') or ''
                    
                    # 检查是否为目标下载按钮的特征
                    is_target_button = False
                    
                    # 1. 检查是否包含"立即下载"文本
                    if '立即下载' in text:
                        is_target_button = True
                        self.logger.info(f"找到包含'立即下载'文本的按钮: {text}")
                    
                    # 2. 检查是否有go-down class
                    elif 'go-down' in class_lower:
                        is_target_button = True
                        self.logger.info(f"找到包含'go-down' class的按钮: {class_attr}")
                    
                    # 3. 检查是否有btn--secondary class组合
                    elif 'btn--secondary' in class_lower and 'btn--block' in class_lower:
                        is_target_button = True
                        self.logger.info(f"找到包含btn--secondary和btn--block class的按钮: {class_attr}")
                    
                    # 4. 检查是否有target="_blank"属性且包含下载相关文本
                    elif target == '_blank' and any(keyword in text_lower for keyword in ['下载', 'download']):
                        is_target_button = True
                        self.logger.info(f"找到target='_blank'的下载按钮: {text}")
                    
                    # 5. 检查是否包含FontAwesome下载图标
                    elif await self._has_download_icon(button):
                        is_target_button = True
                        self.logger.info(f"找到包含下载图标的按钮: {text}")
                    
                    # 6. 通用下载关键词检查
                    else:
                        download_keywords = ['下载', 'download', '获取', 'get', '安装', 'install']
                        if any(keyword in text_lower for keyword in download_keywords):
                            is_target_button = True
                            self.logger.info(f"找到包含下载关键词的按钮: {text}")
                    
                    if is_target_button:
                        button_info = await self._get_button_info(button, 'smart_search', 'download')
                        if await self._validate_download_button(button_info):
                            self.logger.info(f"智能搜索找到有效下载按钮: {text}")
                            return button_info
                            
                except Exception as e:
                    self.logger.debug(f"智能搜索按钮失败: {str(e)}")
            
            return None
            
        except Exception as e:
            self.logger.error(f"智能查找下载按钮失败: {str(e)}")
            return None
    
    async def _has_download_icon(self, button) -> bool:
        """
        检查按钮是否包含下载图标
        
        Args:
            button: 按钮元素
            
        Returns:
            bool: 是否包含下载图标
        """
        try:
            # 检查是否包含FontAwesome下载图标
            icon_selectors = [
                'i.fa-cloud-download',
                'i.fa-download',
                'i[class*="download"]',
                '.fa-cloud-download',
                '.fa-download',
                '[class*="download-icon"]'
            ]
            
            for selector in icon_selectors:
                icon = await button.query_selector(selector)
                if icon:
                    return True
            
            return False
            
        except Exception as e:
            self.logger.debug(f"检查下载图标失败: {str(e)}")
            return False
    
    async def _smart_find_play_button(self) -> Optional[Dict[str, Any]]:
        """
        智能查找游戏按钮
        
        Returns:
            Dict: 按钮信息
        """
        try:
            all_buttons = await self.page.query_selector_all('button, a, input[type="button"], input[type="submit"]')
            
            for button in all_buttons:
                try:
                    if not await button.is_visible():
                        continue
                    
                    text = await button.text_content()
                    if not text:
                        continue
                    
                    text_lower = text.lower()
                    
                    play_keywords = ['游戏', 'play', '开始', 'start', '进入', 'enter', '立即', 'now']
                    if any(keyword in text_lower for keyword in play_keywords):
                        button_info = await self._get_button_info(button, 'smart_search', 'play')
                        if await self._validate_play_button(button_info):
                            self.logger.info(f"智能搜索找到游戏按钮: {text}")
                            return button_info
                            
                except Exception as e:
                    self.logger.debug(f"智能搜索游戏按钮失败: {str(e)}")
            
            return None
            
        except Exception as e:
            self.logger.error(f"智能查找游戏按钮失败: {str(e)}")
            return None
    
    async def find_and_click_download_button(self) -> bool:
        """
        查找并点击下载按钮，并处理可能出现的下载对话框
        
        Returns:
            bool: 是否成功找到并点击下载按钮
        """
        try:
            # 查找下载按钮
            button_info = await self.find_download_button()
            
            if not button_info:
                self.logger.warning("未找到下载按钮")
                return False

            # 点击下载按钮
            click_result = await self.click_download_button(button_info)
            
            if not click_result.get('success', False):
                self.logger.error(f"点击下载按钮失败: {click_result.get('error', 'Unknown error')}")
                return False
            
            self.logger.info("成功点击下载按钮，等待下载对话框...")
            
            # 等待下载对话框出现
            dialog_result = await self._wait_and_handle_download_dialog()
            
            if dialog_result.get('success', False):
                self.logger.info("成功处理下载对话框")
                return True
            else:
                self.logger.warning(f"下载对话框处理结果: {dialog_result.get('message', '未知')}")
                # 即使对话框处理失败，下载按钮点击成功也算成功
                return True
                
        except Exception as e:
            self.logger.error(f"查找并点击下载按钮失败: {str(e)}")
            return False

    async def _wait_and_handle_download_dialog(self, timeout: int = 15000) -> Dict[str, Any]:
        """
        等待并处理下载对话框
        
        Args:
            timeout: 等待超时时间（毫秒）
            
        Returns:
            Dict: 处理结果
        """
        try:
            from .download_dialog_handler import DownloadDialogHandler
            
            dialog_handler = DownloadDialogHandler(self.page)
            
            # 首先等待一段时间让对话框有机会出现
            await asyncio.sleep(1.5)
            
            # 等待对话框出现
            start_time = asyncio.get_event_loop().time()
            dialog_detected = False
            check_interval = 0.3  # 更频繁的检查间隔
            
            self.logger.info(f"开始等待下载对话框，超时时间: {timeout/1000}秒")
            
            while (asyncio.get_event_loop().time() - start_time) * 1000 < timeout:
                dialog_info = await dialog_handler.detect_download_dialog()
                
                if dialog_info:
                    dialog_detected = True
                    self.logger.info(f"检测到下载对话框: {dialog_info.get('dialog_type', 'unknown')}")
                    
                    # 额外等待确保对话框完全加载
                    if dialog_info.get('is_swal2', False):
                        self.logger.info("检测到SweetAlert2对话框，等待动画完成")
                        await asyncio.sleep(1.0)
                    
                    # 处理对话框
                    handle_result = await dialog_handler.handle()
                    
                    if handle_result.get('success', False):
                        return {
                            'success': True,
                            'message': '成功处理下载对话框',
                            'dialog_info': dialog_info,
                            'handle_result': handle_result
                        }
                    else:
                        return {
                            'success': False,
                            'message': f"处理下载对话框失败: {handle_result.get('error', 'Unknown error')}",
                            'dialog_info': dialog_info,
                            'handle_result': handle_result
                        }
                
                # 等待后重试
                await asyncio.sleep(check_interval)
            
            if not dialog_detected:
                self.logger.warning(f"等待{timeout/1000}秒未检测到下载对话框")
                return {
                    'success': False,
                    'message': f'等待{timeout/1000}秒未检测到下载对话框'
                }
            
        except Exception as e:
            self.logger.error(f"等待和处理下载对话框失败: {str(e)}")
            return {
                'success': False,
                'error': str(e),
                'message': '处理下载对话框时发生异常'
            }

    async def click_download_button(self, button_info: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        点击下载按钮（使用专门的识别器）
        
        Args:
            button_info: 按钮信息，如果为None则自动查找
            
        Returns:
            Dict: 点击结果
        """
        try:
            # 记录点击前的页面数量
            initial_pages = len(self.page.context.pages)
            
            # 使用专门的下载按钮识别器
            click_result = await self.download_recognizer.click_download_button(button_info)
            
            if not click_result.get('success'):
                return click_result
            
            # 等待可能的新标签页出现
            await asyncio.sleep(2)
            
            # 检查是否有新标签页
            current_pages = self.page.context.pages
            if len(current_pages) > initial_pages:
                self.logger.info(f"检测到新标签页，从 {initial_pages} 个增加到 {len(current_pages)} 个")
                
                # 获取最新的标签页
                new_page = current_pages[-1]
                
                # 等待新页面加载
                try:
                    await new_page.wait_for_load_state('networkidle', timeout=10000)
                    await asyncio.sleep(1)
                    
                    # 检查新页面类型
                    new_page_result = await self._handle_new_page(new_page)
                    click_result['new_page_result'] = new_page_result
                    
                except Exception as e:
                    self.logger.warning(f"处理新标签页失败: {str(e)}")
                    click_result['new_page_error'] = str(e)
            
            return click_result
            
        except Exception as e:
            self.logger.error(f"点击下载按钮失败: {str(e)}")
            return {'success': False, 'error': str(e)}
    
    async def _handle_new_page(self, new_page) -> Dict[str, Any]:
        """
        处理新打开的页面
        
        Args:
            new_page: 新页面对象
            
        Returns:
            Dict: 处理结果
        """
        try:
            page_url = new_page.url
            page_title = await new_page.title()
            
            self.logger.info(f"处理新页面: {page_url}")
            self.logger.info(f"新页面标题: {page_title}")
            
            # 检查页面内容，判断是密码保护页面还是百度网盘页面
            page_content = await new_page.content()
            
            # 检查是否为密码保护页面
            if '密码保护' in page_content:
                self.logger.info("检测到密码保护页面")
                
                # 导入密码保护页面处理器
                from .password_protected_page_handler import PasswordProtectedPageHandler
                
                # 创建处理器并处理页面
                password_handler = PasswordProtectedPageHandler(new_page)
                result = await password_handler.handle()
                
                return {
                    'page_type': 'password_protected_page',
                    'url': page_url,
                    'title': page_title,
                    'handler_result': result
                }
            
            # 检查是否为百度网盘页面
            elif 'pan.baidu.com' in page_url or '百度网盘' in page_content or '提取码' in page_content:
                self.logger.info("检测到百度网盘页面")
                
                return {
                    'page_type': 'baidu_netdisk',
                    'url': page_url,
                    'title': page_title,
                    'message': '检测到百度网盘页面，等待任务3.3处理'
                }
            
            else:
                self.logger.warning("未知的新页面类型")
                
                return {
                    'page_type': 'unknown',
                    'url': page_url,
                    'title': page_title,
                    'message': '未知的页面类型'
                }
                
        except Exception as e:
            self.logger.error(f"处理新页面失败: {str(e)}")
            return {
                'page_type': 'error',
                'error': str(e)
            }
    
    async def click_play_button(self, button_info: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        点击游戏按钮
        
        Args:
            button_info: 按钮信息，如果为None则自动查找
            
        Returns:
            Dict: 点击结果
        """
        try:
            if not button_info:
                button_info = await self.find_play_button()
            
            if not button_info:
                return {'success': False, 'error': '未找到游戏按钮'}
            
            element = button_info['element']
            
            await element.scroll_into_view_if_needed()
            await asyncio.sleep(0.5)
            
            await element.click()
            self.logger.info(f"点击游戏按钮: {button_info.get('text', 'Unknown')}")
            
            await asyncio.sleep(1)
            
            popups_after = await self.check_for_popups()
            
            return {
                'success': True,
                'button_text': button_info.get('text'),
                'button_selector': button_info.get('selector'),
                'popups_after_click': popups_after,
                'has_new_popups': len(popups_after) > 0
            }
            
        except Exception as e:
            self.logger.error(f"点击游戏按钮失败: {str(e)}")
            return {'success': False, 'error': str(e)}
    
    async def check_page_status(self) -> Dict[str, Any]:
        """
        检查页面状态
        
        Returns:
            Dict: 页面状态信息
        """
        try:
            return {
                'url': self.page.url,
                'title': await self.page.title(),
                'is_loaded': await self.wait_for_page_load(timeout=5000),
                'has_errors': await self._check_for_errors(),
                'element_counts': await self._get_element_counts()
            }
        except Exception as e:
            self.logger.error(f"检查页面状态失败: {str(e)}")
            return {'error': str(e)}
    
    async def _check_for_errors(self) -> bool:
        """
        检查页面是否有错误
        
        Returns:
            bool: 是否有错误
        """
        try:
            error_indicators = [
                '.error', '.alert-error', '.warning',
                'text="404"', 'text="500"', 'text="错误"',
                'text="Error"', 'text="Not Found"'
            ]
            
            for indicator in error_indicators:
                element = await self.page.query_selector(indicator)
                if element and await element.is_visible():
                    return True
            
            return False
            
        except Exception as e:
            self.logger.debug(f"检查错误失败: {str(e)}")
            return False
    
    async def _get_element_counts(self) -> Dict[str, int]:
        """
        获取页面元素统计
        
        Returns:
            Dict: 元素数量统计
        """
        try:
            return await self.page.evaluate("""
                () => {
                    return {
                        buttons: document.querySelectorAll('button').length,
                        links: document.querySelectorAll('a').length,
                        images: document.querySelectorAll('img').length,
                        inputs: document.querySelectorAll('input').length,
                        forms: document.querySelectorAll('form').length
                    };
                }
            """)
        except Exception as e:
            self.logger.debug(f"获取元素统计失败: {str(e)}")
            return {}
    
    async def get_recommended_action(self, download_button: Optional[Dict], play_button: Optional[Dict], page_type: str) -> str:
        """
        获取推荐操作
        
        Args:
            download_button: 下载按钮信息
            play_button: 游戏按钮信息
            page_type: 页面类型
            
        Returns:
            str: 推荐操作
        """
        if download_button and page_type in ['download_page', 'mixed_page']:
            return 'click_download_button'
        elif play_button and page_type == 'play_page':
            return 'click_play_button'
        elif download_button:
            return 'click_download_button'
        elif play_button:
            return 'click_play_button'
        else:
            return 'manual_inspection_needed'